var connection = require('./connect');
var util = require('../util');
var session = require('express-session');
var async = require('async');

module.exports = {
  managerLogin: function(req, res, next){
     var userId = req.body.uid, password = req.body.password;
    res.send('you viewed this page ' + '/managerLogin' + ' times')
    console.log(userId+" "+password);
       connection.query("SELECT * FROM users WHERE u_id='"+userId+"' AND u_password='"+password+"'", function(err, rows, fields) {
         if (err) {
           throw err;
         }else {
           if(rows.length < 1) {
             res.send({status:404,message:"用户名或密码错误，请核实后再登录"});
           } else {
             connection.query("SELECT r_action,u_id,u_nickname,u_logo FROM users RIGHT JOIN user_role ON users.u_role=user_role.r_id WHERE u_id='"+userId+"'", function(err, rows, fields) {
               if (err) {
                 throw err;
               } else {
                 var data = rows[0];
                 if(data.r_action.indexOf('2')<0){res.send({status:403,message:"无操作权限，请联系管理员"});}
                 else {
                   req.session.user = {"userName":data.u_nickname,"userId":data.u_id,"userLogo":data.u_logo};
                   console.log(req.session.user);
                   res.send({status:200,data:data});
                 }
               }
             });
           };
         }
       });
    },
    getLeaderForId: function(req, res, next){
      var userId = req.body.userId;
      connection.query("SELECT u_nickname,u_logo,u_position FROM users WHERE u_id='"+userId+"'", function(err, rows, fields) {
        if (err) {
          throw err;
        }else {
          res.send({status:200,data:rows[0]});
        }
      });
    },
    checkLogin: function(req, res, next){
      console.log(req.session.user);
      if(req.session.user != "" && req.session.user != undefined) {
        res.send({status:200,data:req.session.user});
      } else {res.send({status:201});}
    },
    addSchedule: function(req, res, next){
      var l_id = util.guid(),addData=req.body;
      connection.query("INSERT INTO leader_timeline VALUES ('"+l_id+"', '1', '"+addData.userId+"', '"+addData.title+"', '"+addData.beginTime+"', '"+addData.address+"', '"+addData.desc+"')", function(err, rows, fields) {
        if (err) {
          throw err;
        } else {
          res.send({status:200,message:"添加成功"});
        }
      });
    },
    getFutureSchedule:function(req, res, next){
      var userId = req.body.userId;
      var date = new Date();
      var year = date.getFullYear(),month = date.getMonth() + 1,day = date.getDate();
      var datetime = year + "-" + month + "-" + (day+3) + " 00:00:00";
      connection.query("SELECT * FROM leader_timeline WHERE l_leaderid='"+userId+"' AND l_time >'" + datetime + "' ORDER BY l_time ASC", function(err, rows, fields) {
        if (err) {
          throw err;
        }else {
          for(var i = 0; i<rows.length; i++){
            var tempTime = rows[i].l_time;
            rows[i].l_time = tempTime.getFullYear() + "-" + util.formatNumber(tempTime.getMonth() + 1) + "-" + util.formatNumber(tempTime.getDate())+ " " + util.formatNumber(tempTime.getHours()) + ":" + util.formatNumber(tempTime.getMinutes());
          }
          res.send({data:rows,status:200});
        }
      });
    },
    deleteTimeline:function(req, res, next){
      var timelineId = req.body.timelineId;
      var date = new Date();
      console.log("timelineId:",timelineId);
      connection.query("DELETE FROM leader_timeline WHERE l_id='"+timelineId+"'", function(err, rows, fields) {
        if (err) {
          throw err;
        }else {
          res.send({message:"删除成功",status:200});
        }
      });
    },
    updateTimeline:function(req, res, next){

      var timelineId = req.body.timelineId,title = req.body.title,desc = req.body.desc,address = req.body.address,time = req.body.time;
      var sql = "UPDATE leader_timeline SET l_matter='"+title+"',l_desc='"+desc+"',l_address='"+address+"',l_time='"+time+"' WHERE l_id='"+timelineId+"'";
      console.log(sql);
      connection.query(sql, function(err, rows, fields) {
        console.log(rows);
        if (err) {
          throw err;
        }else {
          res.send({message:"更新成功",status:200});
        }
      });
    },
    getSchedule: function(req, res, next){
      var userId = req.body.userId;
      console.log(userId);
      // 获取过去三天及未来三天日程安排
      var date = new Date();
      var year = date.getFullYear(),month = date.getMonth() + 1,day = date.getDate();
      var scheduleList = [];
      var arr = [
           {minTime:year + "-" + month + "-" + (day-2) + " 00:00:00", maxTime:year + "-" + month + "-" + (day-1) + " 00:00:00"},
          {minTime:year + "-" + month + "-" + (day-1) + " 00:00:00", maxTime:year + "-" + month + "-" + (day) + " 00:00:00"},
          {minTime:year + "-" + month + "-" + (day) + " 00:00:00", maxTime:year + "-" + month + "-" + (day+1) + " 00:00:00"},
          {minTime:year + "-" + month + "-" + (day+1) + " 00:00:00", maxTime:year + "-" + month + "-" + (day+2) + " 00:00:00"},
          {minTime:year + "-" + month + "-" + (day+2) + " 00:00:00", maxTime:year + "-" + month + "-" + (day+3) + " 00:00:00"}
        ];
        var length = 0;
      async.each(arr, function(item, callback) {
        connection.query("SELECT * FROM leader_timeline WHERE l_leaderid='"+userId+"' AND l_time BETWEEN '" + item.minTime + "' AND '" + item.maxTime + "' ORDER BY l_time ASC", function(err, rows, fields) {
          if (err) {
            throw err;
          }else {
            var datetime = item.minTime.split(' ')[0];
            if(rows == [] || rows== "" || rows == null){
              scheduleList.push({date:datetime,message:"当日无日程数据",status:202});
            } else {
              for(var i = 0; i<rows.length; i++){
                var tempTime = rows[i].l_time;
                rows[i].l_time = util.formatNumber(tempTime.getHours()) + ":" + util.formatNumber(tempTime.getMinutes());
              }
              scheduleList.push({date:datetime,data:rows,status:200});
            }
            length++;
            if(length == 5) {res.send({status:200,data:scheduleList});
          }
          };
        });
      }, function(err) {
          consle.log("同步查询出现错误！");
      });
    }
};
